from fastapi import APIRouter, Depends, HTTPException, Query
from sqlalchemy.orm import Session
from typing import List
from app.core.database import get_db
from app.crud.history import history
from app.models.history import HistoryType
from app.schemas.history import HistoryResponse, HistoryCreate
from loguru import logger

router = APIRouter()

@router.post("/prompt", response_model=HistoryResponse)
async def create_prompt_history(
    history_in: HistoryCreate,
    db: Session = Depends(get_db)
):
    """创建提示词生成历史"""
    try:
        history_record = history.create_prompt_history(
            db,
            input_text=history_in.input_text,
            output_text=history_in.output_text,
            parameters=history_in.parameters
        )
        return history_record
    except Exception as e:
        logger.error(f"创建提示词历史失败: {str(e)}")
        raise HTTPException(status_code=500, detail="创建历史记录失败")

@router.post("/chat", response_model=HistoryResponse)
async def create_chat_history(
    history_in: HistoryCreate,
    db: Session = Depends(get_db)
):
    """创建对话历史"""
    try:
        history_record = history.create_chat_history(
            db,
            input_text=history_in.input_text,
            output_text=history_in.output_text,
            parameters=history_in.parameters
        )
        return history_record
    except Exception as e:
        logger.error(f"创建对话历史失败: {str(e)}")
        raise HTTPException(status_code=500, detail="创建历史记录失败")

@router.get("/", response_model=List[HistoryResponse])
async def get_history(
    history_type: HistoryType = None,
    skip: int = Query(0, ge=0),
    limit: int = Query(10, ge=1, le=100),
    db: Session = Depends(get_db)
):
    """获取历史记录"""
    try:
        if history_type:
            records = history.get_history_by_type(db, history_type, skip, limit)
        else:
            records = history.get_multi(db, skip=skip, limit=limit)
        return records
    except Exception as e:
        logger.error(f"获取历史记录失败: {str(e)}")
        raise HTTPException(status_code=500, detail="获取历史记录失败")

@router.get("/recent", response_model=List[HistoryResponse])
async def get_recent_history(
    limit: int = Query(10, ge=1, le=100),
    db: Session = Depends(get_db)
):
    """获取最近的历史记录"""
    try:
        records = history.get_recent_history(db, limit)
        return records
    except Exception as e:
        logger.error(f"获取最近历史记录失败: {str(e)}")
        raise HTTPException(status_code=500, detail="获取历史记录失败") 